<template>
  <el-form
    ref="ruleFormRef"
    :model="regForm"
    :rules="rules"
    label-width="120px"
    status-icon
  >

    <el-form-item :label="$t('common.reg.userName')" prop="name">
      <el-input v-model="regForm.name" autocomplete="off" />
    </el-form-item>

    <el-form-item
      :label="$t('common.reg.phoneNumber')"
      prop="mobile">
      <el-input v-model="regForm.mobile">
        <template #append>
          <el-button v-if="countDown===61 || countDown===0" @click="getCaptcha">
            {{ $t("common.reg.getCaptcha") }}
          </el-button>
          <el-button v-else disabled>{{ countDown }}</el-button>
        </template>
      </el-input>
    </el-form-item>

    <el-form-item :label="$t('common.reg.pwd')" prop="password">
      <el-input v-model="regForm.password" autocomplete="off" type="password" />
    </el-form-item>


    <el-form-item :label="$t('common.reg.rePwd')" prop="checkPwd">
      <el-input
        v-model="regForm.checkPwd"
        autocomplete="off"
        type="password"
      />
    </el-form-item>

    <el-form-item :label="$t('common.reg.captcha')" prop="captcha">
      <el-input v-model="regForm.captcha" />
    </el-form-item>
    <el-form-item>
      <el-button class="button" type="primary" @click="submitForm(ruleFormRef)"
      >{{ $t("common.reg.submit") }}
      </el-button>

    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import router from "@/router";
import { captchaWithVerify, register, verifyUserNameApi } from "@/utils/api/register";
import { validatePhoneNum } from "@/utils/validation";
import type { FormInstance } from "element-plus";
import { reactive, ref } from "vue";

const ruleFormRef = ref<FormInstance>();
const countDown = ref(61);

const regForm = reactive({
  name: "",
  mobile: "13685208896",
  password: "",
  checkPwd: "",
  captcha: "",
  captcha_id: ""
});


const validateUserName = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入用户名"));
  } else {
    verifyUserNameApi(value).then((res: any) => {
      if (res.data !== "ok") {
        value = "";
        callback(new Error("用户名已存在"));
      } else {
        callback();
      }
    }).catch((err: any) => {
      callback(new Error("用户名校验失败"));
    });
  }

};

const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请重新输入密码"));
  } else if (value !== regForm.password) {
    callback(new Error("两次输入的密码不匹配哟"));
  } else {
    callback();
  }
};

function countdown() {
  countDown.value--;
  var timer = setInterval(function() {
    countDown.value--; // 每次执行时，将倒计时的值减1
    if (countDown.value === 0) {
      clearInterval(timer); // 如果倒计时结束，清除定时器
      countDown.value = 61;
    }
  }, 1000); // 每隔1秒执行一次
}

const getCaptcha = () => {
  countdown();
  captchaWithVerify(regForm.mobile).then((res: any) => {
    regForm.captcha_id = res.data.uuid;
    console.log(regForm.captcha_id);
  });
};

const validatePhoneNumAndSendCaptcha = (rule: any, value: any, callback: any) => {
  validatePhoneNum(rule, value, callback);
  if (regForm.captcha_id === "") {
    getCaptcha();
  }

};

const rules = reactive({
  name: [{ required: true, validator: validateUserName, trigger: "blur" }],
  mobile: [{ required: true, validator: validatePhoneNumAndSendCaptcha, trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  checkPwd: [{ required: true, validator: validatePass2, trigger: "blur" }],
  captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }]
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      register(regForm.name, regForm.mobile, regForm.password, regForm.captcha, regForm.captcha_id).then(res => {
        console.log(res);
        router.push("/login");
      }).catch(err => {
        console.log(err);
      });

    } else {
      console.log("提交错误");
      return false;
    }
  });
};


</script>
